//
//  StartViewController.swift
//  MMTest
//
//  Created by liujianlong on 2022/10/20.
//

import UIKit
import AudioToolbox
class StartViewController: EPViewController {
    @IBOutlet var bgview: UIView!
    @IBOutlet var leftView: RecordView!
    @IBOutlet var rightView: RecordView!
    @IBOutlet var cycle: PieView!
    @IBOutlet var btn: UIButton!
    
    @IBOutlet var time: UILabel!
    @IBOutlet var kpa: UILabel!
    @IBOutlet var altitude: UILabel!
    @IBOutlet var state: UILabel!
    var switchBtn = UISwitch()
    var switchTitle = UILabel(frame: CGRect(x:2, y:(31-12)/2, width: 47, height: 12))
    var singleStart = false
    var tempValue = 2000
    var endStamp = 0
    var total_avg : CGFloat = 0
    var fatigue : Int = 0 ///疲劳值
    var isRelax : Bool = false///是否疲劳状态
    
    var timer: DispatchSourceTimer?
    
    var relaxStart:Int = 0///放松状态，开始的时间
    var fatigueStart:Int = 0 ///疲劳状态开始的时间
    
    @IBOutlet var fatigueLbl: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        self.countdown()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotifyTool.remove(self)
    }
    override func initUI() {
        self.title = LS("记录中")
        let w = kUIScreenWidth / 3
        self.cycle.bounds = CGRect(x:0, y: 0, width: w, height: w + 22)
        self.bgview.shadow("#CFCFCF".color(), CGSize(width:1, height:1), 6, 6)
        self.leftView.shadow("#CFCFCF".color(), CGSize(width:1, height:1), 6, 6)
        self.rightView.shadow("#CFCFCF".color(), CGSize(width:1, height:1), 6, 6)
        self.btn.shadow("#999999".color(), CGSize(width:1, height:1), 6, 6)
        
        self.switchBtn.onTintColor = "#00DCDE".color()
        self.switchBtn.isOn = true
        self.switchBtn.addTarget(self, action: #selector(actionForSwitch), for: .touchUpInside)
        self.switchTitle.font = font(10)
        self.switchTitle.text = LS("震动")
        self.switchTitle.isUserInteractionEnabled = false
        self.switchTitle.textAlignment = self.switchBtn.isOn ? .left:.right
        self.switchBtn.addSubview(self.switchTitle)
        let backItem = UIBarButtonItem(customView:self.switchBtn)
        self.navigationItem.rightBarButtonItem = backItem
        self.backBtn?.isHidden = true
    }
    
    func updateUI(){
        let p_r = APP.singleData.r_total_avg == 0.0 || self.total_avg == 0.0 ? 0 : Int(roundf(Float(APP.singleData.r_total_avg / (self.total_avg)) * 100))
        let p_l = APP.singleData.l_total_avg == 0.0 || self.total_avg == 0.0 ? 0 : Int(roundf(Float(APP.singleData.l_total_avg / (self.total_avg)) * 100))
        self.cycle.percents = [p_l,p_r]
        self.kpa.text = "\(RecordView.num(APP.singleData.airPressure))"
        self.altitude.text = "\(RecordView.num(Int32(APP.singleData.altitude)))"
        self.leftView.p = p_l
        self.rightView.p = p_r
        self.leftView.isLeft = true
        self.rightView.isLeft = false
        self.leftView.model = APP.singleData
        self.rightView.model = APP.singleData
       
        ///更新疲劳值
        switch self.fatigue{
        case 0...1000:
            
            self.state.text = "轻松"
            self.state.textHexColor = "#00DCDE"
        case 1001...2000:
            self.state.text = "疲劳"
            self.state.textHexColor = "#FF8A00"
        case 2001...:
            self.state.text = "透支"
            self.state.textHexColor = "#FA2C2C"
        default:
            break
        }
        self.fatigueLbl.text = "当前疲劳值"+"\n\(self.fatigue)"
    }
    
    ///定时器
    func countdown(){
        self.endStamp = APP.stamp.intValue()
        self.timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        self.timer!.schedule(deadline: .now(), repeating:1)
        self.timer!.setEventHandler {
            DispatchQueue.main.async {
                self.endStamp += 1
                let t = self.endStamp - APP.stamp.intValue()
                let hour = t / 3600
                let min = t % 3600 / 60
                let sec = t % 3600 % 60
                self.time.text = String(format:"%02d:%02d:%02d", hour,min,sec)
                
                ///随时判断是否超过10秒还没有有效压力值，没有则进入放松模式
                var num = 0
                num = self.endStamp - APP.singleData.stamp.intValue() > 10 ? num + 1 : num
                
                if num == 0{
                    self.isRelax = true
                    self.relaxStart = self.relaxStart == 0 ? self.endStamp : self.relaxStart
                }else{
                    self.isRelax = false
                    self.relaxStart = 0
                }
                print(">>>>>>>>>>>>  num ;\(num)  count: start:\(self.relaxStart)")
                ///放松状态,每30秒减少5个疲劳值
                if self.isRelax && self.endStamp > self.relaxStart && (self.endStamp - self.relaxStart)%30 == 0{
                    self.fatigue = self.fatigue >= 5 ? self.fatigue - 5 : 0
                }
                
                ///震动提示
                let value = self.endStamp - self.fatigueStart
                switch (self.fatigue,value%600,value%300,self.switchBtn.isOn){
                case(1001...2000,0,_,true),(2001...,_,0,true):
                    self.shake(0)
                default:
                    break
                }
                
                
            }
        }
        self.timer!.resume()
    }
    ///结束按钮
    @IBAction func actionForBtn(_ sender: UIButton) {
        if self.record.data.count <= 0{
            self .alert("注意", "当前没有任何有效数据，确定要离开吗?") {
                
            } _: {
                self.navigationController?.popViewController(animated: true)
            }
            return
        }
        APP.start = false
        APP.singleData.num = 0
        
        let vc = EndViewController()
        self.record.endTime = NSDate.transToDate("yyyy-MM-dd HH:mm:ss", self.endStamp)
        vc.record = self.record
        self.switchBtn.isOn = false
        self.push(vc, true)
    }
    ///震动开关按钮
    @objc func actionForSwitch(_ swb:UISwitch){
        self.switchTitle.textAlignment = self.switchBtn.isOn ? .left:.right
        if swb.isOn{
            AudioServicesPlaySystemSound(1521)
        }
    }
    
    ///震动开关按钮
    func shake(_ num:Int){
        if self.switchBtn.isOn == false  || num > 2{
            AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate)
            return
        }
        AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate) {
            DispatchQueue.main.async {
                self.shake(num+1)
            }
        }
    }
    
    lazy var record : Record = {
        let model = Record()
        model.data = NSMutableArray()
        model.recordId = Int32(APP.stamp.intValue())
        model.startTime = NSDate.transToDate("yyyy-MM-dd HH:mm:ss", Int(model.recordId))
        return model
    }()
    
}

//MARK: - 蓝牙相关通知
extension StartViewController{
    override func addNotify() {
        NotifyTool.add(self, #selector(actionForBLEStatusUpdate), BLEStatusUpdateNotifyName)
        NotifyTool.add(self, #selector(actionForBLESDataUpdate), BleDataUpdateNotifyName)
    }
    
    @objc func actionForBLEStatusUpdate(){
        DispatchQueue.main.async {
            if BLE.status == .connectedFail{
                self.pop(LS("提示"), LS("蓝牙已断开！"), .onlyOK) { tag, text in
                    self.navigationController?.popToRootViewController(animated: true)
                }
            }}
    }
    
    @objc func actionForBLESDataUpdate(_ notify:Notification){
        let mac = notify.object as? String ?? ""
        if APP.singleData.mac == mac && APP.start{
            ///每次开始
            if APP.singleData.start == false && (APP.singleData.l_current > self.tempValue || APP.singleData.r_current > self.tempValue){
                self.isRelax = false
                APP.singleData.start = true
                APP.singleData.l_data = NSMutableString()
                APP.singleData.l_max_data = 0
                APP.singleData.r_data = NSMutableString()
                APP.singleData.r_max_data = 0
                APP.singleData.startStamp = APP.stamp
                APP.singleData.stamp =  NSDate.currentTimeStamp("yyyy/MM/dd HH:mm:ss")
            }
            ///每次结束
            else if APP.singleData.start && APP.singleData.l_current <= self.tempValue && APP.singleData.r_current <= self.tempValue{
                APP.singleData.start = false
                APP.singleData.num += 1
                let new_m = APP.singleData.copy()
                self.record.data.add(new_m)
                APP.singleData.l_total_avg = APP.singleData.l_total_avg + APP.singleData.l_avg
                APP.singleData.r_total_avg = APP.singleData.r_total_avg + APP.singleData.r_avg
                self.total_avg = self.total_avg + APP.singleData.l_avg + APP.singleData.r_avg;
                
                ///每杆结束，如果不是放松状态，根据最高压力值，计算疲劳值
                if !self.isRelax{
                    var n = 0
                    switch (APP.singleData.l_max_data,APP.singleData.r_max_data){
                    case (0...4000,0...4000):
                        n = 1
                    case (4001...8000,4001...8000):
                        n = 2
                    default:
                        n = 3
                    }
                    
                    ///获取疲劳值越过，疲劳/透支的阀值，瞬间的时间
                    switch (self.fatigue,self.fatigue+n){
                    case (0...1000, 1001...2000),(0...2000,2001...):
                        self.fatigueStart = NSDate.currentTimeStamp("yyyy-MM-dd HH:mm:ss").intValue()
                    default:
                        break
                    }
                    self.fatigue += n
                }
                print("\n\n\n每次结束 >>>>>>>>>> mac:\(APP.singleData.mac) ---------次数:\(APP.singleData.num)  \n单次平均受力L:\(APP.singleData.l_avg)\n单次平均受力R:\(APP.singleData.r_avg)------累计受力L:\(APP.singleData.l_total_avg)------累计受力R:\(APP.singleData.r_total_avg) --------双杖累计受力:\(self.total_avg)\n>>>>>>压力值L:\(APP.singleData.l_data)\n>>>>>>压力值R:\(APP.singleData.r_data)  >>>>>>疲劳值：\(self.fatigue)")
            }
            
            if APP.start && (APP.singleData.l_current >= self.tempValue || APP.singleData.r_current >= self.tempValue){
                let temp = NSMutableString(string: APP.singleData.l_data)
                temp.append("\(APP.singleData.l_current)"+",")
                APP.singleData.l_data = NSMutableString(string: temp)
                APP.singleData.l_max_data = APP.singleData.l_max_data <= APP.singleData.l_current ? APP.singleData.l_current : APP.singleData.l_max_data
                
                let temp2 = NSMutableString(string: APP.singleData.r_data)
                temp2.append("\(APP.singleData.r_current)"+",")
                APP.singleData.r_data = NSMutableString(string: temp2)
                APP.singleData.r_max_data = APP.singleData.r_max_data <= APP.singleData.r_current ? APP.singleData.r_current : APP.singleData.r_max_data
            }
        }
        DispatchQueue.main.async {
            self.updateUI()
        }
    }
}

